package main

import (
	"fmt"
	"net"
	"log"
	"encoding/binary"
	"github.com/fananchong/cstruct-go"
)

type EventMessage struct {
	id 	uint8
	class	uint8 
	para	uint16
	length  uint32
}


func handleConnection(conn net.Conn) {
    defer conn.Close()
    buf := make([]byte, 8)
    for {
	data := EventMessage{}
        n, err := conn.Read(buf)
        if err != nil {
            log.Println(err)
            return
        }

	err = cstruct.Unmarshal(buf, &data)
        if err != nil {
                fmt.Println(err.Error())
        }
	
	var testByte []byte = make([]byte, 4)
	binary.BigEndian.PutUint32(testByte, data.length)
	convInt := binary.LittleEndian.Uint32(testByte)
	data.length = convInt;	
	
	body := make([]byte, data.length + 2)
        n, err = conn.Read(body)
        if err != nil {
            log.Println(err)
            return
        }
	fmt.Printf("%s\n", string(body[:n - 2]))
    }
}

func main() {

	addr, err := net.ResolveTCPAddr("tcp", ":8800")
	if err != nil {
		log.Fatal(err)
	}
	ln, err := net.ListenTCP("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()
	fmt.Println("Listening on port 8800")
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go handleConnection(conn)
	}
}
